//
//  MyInvateViewController.m
//  TuDianEducation
//
//  Created by lixinkeji on 2021/1/11.
//  Copyright © 2021 zhangbenchao. All rights reserved.
//

#import "MyInvateViewController.h"
#import "BkInvateTableViewCell.h"
#import "BkInvateHearderView.h"
#import "LXSaveUserInforTool.h"
#import "BkMyUnderViewController.h"

@interface MyInvateViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic) NSInteger pageNum;
@property (nonatomic,strong) BkInvateHearderView *headerView;

@property (nonatomic,strong) NSString *shareUrl;

@end

@implementation MyInvateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = kSubBacColor;
    
    
    [self addRightNavItemWithTitle:@"邀请规则" color:kSubTxtColor font:systemFont(TSScaleW(13))];
    self.title = @"我的邀请";
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self headerRefresh];
    [self userInforRequstAction];
}
#pragma mark ---邀请规则
-(void)rigthBtnAction:(id)sender{
    [self gotoWebWithUrl:kUserDelegateUrlTag(@"7") title:@"邀请规则"];
}

-(void)userInforRequstAction{
    if (kLogin) {
        [NetWorkTools postConJSONWithUrl:@"memberinfo" parameters:@{} success:^(id responseObject) {
            NSString *result = responseObject[@"result"];
            NSString *resultNote = responseObject[@"resultNote"];
            NSDictionary *data = responseObject[@"dataobject"];
            if ([result integerValue] == 0) {
                NSString *  invitationcode = data[@"invitationcode"];
                [LXSaveUserInforTool sharedUserTool].userInforDic = data;
                self.headerView.invateCodeLabel.text = [NSString stringWithFormat:@"邀请码：%@",invitationcode];
                [kUserDefaults setValue:data[@"ismember"] forKey:@"ismember"];
                self.headerView.invateImgView.image = [self creatCIQRCodeImageWithString:[NSString stringWithFormat:@"http://app.daishengbook.com/h5/#/pages/registe/index?invitationcode=%@&type=1",invitationcode]];
                self.shareUrl = [NSString stringWithFormat:@"http://app.daishengbook.com/h5/#/pages/registe/index?invitationcode=%@&type=1",invitationcode];
            }else{
                 [MBProgressHUD showError:resultNote];
            }
                         
        } fail:^(NSError *error) {
            
        }];
    }
   
    
}



-(NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
-(BkInvateHearderView *)headerView{
    if (!_headerView) {
        _headerView = [[BkInvateHearderView alloc]init];
        WS(weakSelf);
        _headerView.commitBlock = ^{
            if (weakSelf.shareUrl.length) {
             
                [TSWLTools shareBtnClickWithImg:nil withTitle:weakSelf.shareUrl withContent:@"欢迎使用戴胜鸟图书" withWebUrl:weakSelf.shareUrl];
            }
           
        };
    }
    return _headerView;
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, TSScreenWidth, TSScreenHeight - Height_NavBar ) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       
        if (@available(iOS 11.0, *))
        {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }
        else
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        WS(weakSelf);
        _tableView.mj_header = [CustomGifHeader headerWithRefreshingBlock:^{
                [weakSelf headerRefresh];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                [weakSelf footerRefresh];
        }];
        _tableView.tableHeaderView = self.headerView;
    }
    return _tableView;
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BkInvateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BkInvateTableViewCell"];
    if (!cell) {
        cell = [[BkInvateTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"BkInvateTableViewCell"];
  
    }
    cell.dataDic = self.dataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.row];
    NSString *userid = dic[@"userid"];
    BkMyUnderViewController *vc = [[BkMyUnderViewController alloc]init];
    vc.state = userid;
    NSString *username = dic[@"username"];
    vc.title = username;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TSScaleW(70);
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]initWithFrame:CGRectZero];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TSScreenWidth, 0)];
    view.backgroundColor = kMainBgColor;
    return view;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return CGFLOAT_MIN;
}

#pragma mark - 上拉、下拉

-(void)headerRefresh
{
    self.pageNum = 1;
    [self collectListReq];
}

-(void)footerRefresh
{
    [self collectListReq];
}
-(void)collectListReq
{
    NSDictionary *pamas = @{@"pageNo":[NSString stringWithFormat:@"%ld",self.pageNum],@"pageSize":[NSString stringWithFormat:@"%d",kPage_Size]};
   

    [NetWorkTools postConJSONWithUrl:@"myfirstinvitationlist" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *array = responseObject[@"dataList"];
        
        NSString *daymoney = responseObject[@"daymoney"];
        NSString *allmoney = responseObject[@"allmoney"];
        self.headerView.todaySaveLabel.text = [NSString stringWithFormat:@"今日收益：%@",daymoney];
        self.headerView.allSaveMoneyLabel.text = [NSString stringWithFormat:@"累计收益：%@",allmoney];
        NSString *allnum = responseObject[@"allnum"];
        self.headerView.myFirendLabel.text = [NSString stringWithFormat:@"我的好友（%@）",allnum];
        if (result.integerValue == 0) {
           
            [self handleListWithModel:array];
        }else{
             [MBProgressHUD showError:resultNote];
        }

    } fail:^(NSError *error) {

    }];
}

-(void)endRefrash

{
    if (self.tableView.mj_header.state == MJRefreshStateRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
    
    if (self.tableView.mj_footer.state == MJRefreshStateRefreshing) {
        [self.tableView.mj_footer endRefreshing];
    }
}
-(void)handleListWithModel:(NSArray *)result
{
    
    if (self.pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    if (result.count != kPage_Size) {
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }else{
        self.tableView.mj_footer.state = MJRefreshStateIdle;
    }
    
    [self.dataArray addObjectsFromArray:result];
   
  // [SSKJ_NoDataView showNoData:self.dataArray.count toView:self.tableView offY:TSScaleW(10) message:@"还没有数据哦~" imge:[UIImage imageNamed:@"nolikesimg"]];
    
    self.pageNum++;
    
    [self endRefrash];
    
    [self.tableView reloadData];
    
}

/**
 *  生成二维码
 */
- (UIImage *)creatCIQRCodeImageWithString:(NSString *)string
{
    // 1.创建过滤器，这里的@"CIQRCodeGenerator"是固定的
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复默认设置
    [filter setDefaults];
    // 3. 给过滤器添加数据
    NSString *dataString = string;
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    // 注意，这里的value必须是NSData类型
    [filter setValue:data forKeyPath:@"inputMessage"];
    // 4. 生成二维码
    CIImage *outputImage = [filter outputImage];
    // 5. 显示二维码
    // 该方法生成的图片较模糊
    //    self.codeImg.image = [UIImage imageWithCIImage:outputImage];
    // 使用该方法生成高清图
    return [self creatNonInterpolatedUIImageFormCIImage:outputImage withSize:self.headerView.invateImgView.width];
}

/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param image CIImage
 *  @param size  图片宽度
 *
 *  @return 生成高清的UIImage
 */
- (UIImage *)creatNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1. 创建bitmap
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
    
}


@end
